document.addEventListener('DOMContentLoaded', function() {
    const orderItemsTable = document.getElementById('orderItemsTable');
    const totalAmount = document.getElementById('totalAmount');
    const payBtn = document.getElementById('payBtn');
    const backBtn = document.getElementById('backBtn');
    const paySuccessModal = document.getElementById('paySuccessModal');
    const viewOrdersBtn = document.getElementById('viewOrdersBtn');
    const feedbackModal = document.getElementById('feedbackModal');
    const feedbackIcon = document.getElementById('feedbackIcon');
    const feedbackTitle = document.getElementById('feedbackTitle');
    const feedbackMessage = document.getElementById('feedbackMessage');
    const feedbackConfirmBtn = document.getElementById('feedbackConfirmBtn');
    
    // 从localStorage获取购物车数据
    const cart = JSON.parse(localStorage.getItem('cart')) || [];
    
    // 获取用户信息
    const user = JSON.parse(localStorage.getItem('user'));
    
    // 显示反馈模态框
    function showFeedback(type, title, message) {
        // 设置图标类型
        feedbackIcon.className = 'feedback-icon ' + type;
        
        // 设置图标内容
        if (type === 'success') {
            feedbackIcon.textContent = '✓';
        } else if (type === 'error') {
            feedbackIcon.textContent = '✗';
        } else {
            feedbackIcon.textContent = 'i';
        }
        
        // 设置标题和消息
        feedbackTitle.textContent = title;
        feedbackMessage.textContent = message;
        
        // 显示模态框
        feedbackModal.style.display = 'block';
    }
    
    // 显示订单信息
    function displayOrderInfo() {
        let total = 0;
        orderItemsTable.innerHTML = '';
        
        if (cart.length === 0) {
            document.querySelector('.order-items').innerHTML = '<p style="text-align: center; color: #666;">购物车为空</p>';
            payBtn.disabled = true;
            payBtn.style.backgroundColor = '#ccc';
            payBtn.style.cursor = 'not-allowed';
            return;
        }
        
        // 显示订单时间
        const orderTime = new Date().toLocaleString();
        document.getElementById('orderTime').textContent = orderTime;
        
        // 显示订单项目
        cart.forEach(item => {
            const itemTotal = parseFloat(item.price) * item.quantity;
            total += itemTotal;
            
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${item.name}</td>
                <td>¥${parseFloat(item.price).toFixed(2)}</td>
                <td>${item.quantity}</td>
                <td>¥${itemTotal.toFixed(2)}</td>
            `;
            
            orderItemsTable.appendChild(row);
        });
        
        totalAmount.textContent = total.toFixed(2);
    }
    
    // 支付功能
    function payOrder() {
        if (!user) {
            alert('请先登录');
            window.location.href = 'login.html';
            return;
        }
        
        // 准备订单数据
        const orderData = {
            user_id: user.user_id,
            order_status: '已支付',
            total_amount: parseFloat(totalAmount.textContent),
            order_details: cart.map(item => ({
                food_id: item.id,
                quantity: item.quantity,
                unit_price: parseFloat(item.price),
                subtotal: parseFloat(item.price) * item.quantity
            }))
        };
        
        // 调用后端API创建订单
        fetch('http://localhost:5000/api/orders', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(orderData)
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('创建订单失败');
            }
            return response.json();
        })
        .then(data => {
            // 清空购物车
            localStorage.removeItem('cart');
            
            // 显示支付成功模态框
            paySuccessModal.style.display = 'block';
        })
        .catch(error => {
                showFeedback('error', '支付失败', error.message);
                console.error('支付错误：', error);
            });
    }
    
    // 获取用户详细信息
    function fetchUserDetails() {
        if (!user) {
            alert('请先登录');
            window.location.href = 'login.html';
            return;
        }
        
        fetch(`http://localhost:5000/api/users/${user.user_id}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('获取用户信息失败');
                }
                return response.json();
            })
            .then(userDetails => {
                document.getElementById('username').textContent = `欢迎，${user.username}`;
                document.getElementById('userName').textContent = userDetails.name || user.username;
                document.getElementById('userContact').textContent = userDetails.phone || '未设置';
                document.getElementById('userAddress').textContent = userDetails.address || '请在个人信息中设置地址';
            })
            .catch(error => {
                console.error('获取用户信息错误：', error);
                // 使用默认值
                document.getElementById('username').textContent = `欢迎，${user.username}`;
                document.getElementById('userName').textContent = user.username;
                document.getElementById('userContact').textContent = '未设置';
                document.getElementById('userAddress').textContent = '请在个人信息中设置地址';
            });
    }
    
    // 事件监听
    payBtn.addEventListener('click', payOrder);
    
    // 反馈模态框确认按钮事件
    feedbackConfirmBtn.addEventListener('click', function() {
        feedbackModal.style.display = 'none';
    });
    
    // 点击模态框外部关闭
    window.addEventListener('click', function(event) {
        if (event.target === feedbackModal) {
            feedbackModal.style.display = 'none';
        }
    });
    
    backBtn.addEventListener('click', function() {
        window.location.href = 'student_home.html';
    });
    
    viewOrdersBtn.addEventListener('click', function() {
        paySuccessModal.style.display = 'none';
        window.location.href = 'student_orders.html';
    });
    
    window.addEventListener('click', function(event) {
        if (event.target === paySuccessModal) {
            paySuccessModal.style.display = 'none';
            window.location.href = 'student_orders.html';
        }
    });
    
    // 初始化页面
    displayOrderInfo();
    fetchUserDetails();
});